﻿'use strict'
var pageFlag = true;
var totalRows = 0;
var pageLimits = [10, 20, 30];


function chargeTpl(tplid, viewid, checkbarParams, append) {
    if (tplid && viewid) {
        var tpl = document.getElementById(tplid).innerHTML, view = document.getElementById(viewid);
        layui.use('laytpl', function () {
            var laytpl = layui.laytpl;
            laytpl(tpl).render(checkbarParams, function (html) {
                if (append)
                    view.innerHTML += html;
                else
                    view.innerHTML = html;
            })
        });
    }
}

//加载更多
function loadMore(params) {
    params.clear = false;
    var pageIndex = params.data.pageIndex;
    var pageSize = params.data.pageSize;
    //params.data.pageIndex = pageIndex + 1;
    if (totalRows <= (pageIndex - 1) * pageSize) {
        layer.msg("没有更多了");
        $("#loadMore").hide();
    }
    else {
        sendAjax(params);
        setTimeout(function () {
            $(".msg_avatar").attr("src", the_avatar);
        }, 200);
    };
}

//发送请求，返回值为{result:-,title:-total:-,description:-,RetValue:-}格式
function sendAjax(params) {
    if (params.rows == null || params.rows == "undefined" || params.rows == "") {
        params.rows = "json.data";
    }
    if (params.contentType == null || params.contentType == "undefined" || params.contentType == "") {
        params.contentType = "application/x-www-form-urlencoded; charset=UTF-8";
    }
    if (params.waitTime == null || params.waitTime == "undefined" || params.waitTime == "") {
        params.waitTime = 1000;
    }
    layui.use('layer', function () {
        layer = layui.layer;
        layer.load();
    });

    //layer.alert(1)
    var asyncType = true;
    if (params.async = false)
        asyncType = false;
    var ret;
    $.ajax({
        url: params.url,
        type: params.type,
        catch: false,
        async: asyncType,
        data: params.data,
        datatype: 'json',
        contentType: params.contentType,
        traditional: true,
        success: function (json) {
            ret = json;
            var msg = json.message;
            if (!msg)
                msg = json.description;
            layui.use('layer', function () {
                layer = layui.layer;
                layer.closeAll('loading');
            });

            if (params.type == 'get' && params.loadmore) {
                if (json.data) {
                    totalRows = json.data.total;
                    if (totalRows > json.data.items.length)
                        $("#loadMore").show();
                    else
                        $("#loadMore").hide();
                }
            }
            if (params.check == 1) {
                if (json.message == "no") {
                    localStorage.clear();
                    window.location.href = "login.html";
                }
            }
            if (json.code == 1 || json.result == 1) {
                if (params.showMsg) {//是否弹出消息

                    if (params.jumpurl) {
                        msg = msg + ",稍后将自动跳转..."
                    }
                    if (params.sweet)
                        swal(msg, { icon: "success" });
                    else
                        layer.msg(msg, { icon: 1 });
                }
                if (params.showAlert) {
                    layer.alert(json.message, function () {
                        window.location.reload();
                    });
                }
                if (params.modelhide) {//是否隐藏模板
                    $(params.modelhide).modal('hide');
                }
                if (params.jumpurl) {//是否跳转链接
                    setTimeout(function () { location.href = params.jumpurl; }, params.waitTime)
                }
                if (params.refresh) {                    
                    setTimeout(function () { window.location.reload(); }, 2000)
                }
            }
            else if (json.code > 1 || json.result > 1) {
                layer.alert(msg, { icon: 0 }, function () {
                    if (params.jumpurl) {//是否跳转链接
                        setTimeout(function () { location.href = params.jumpurl; }, 500)
                    }
                });
            }
            else if (json.code == -2 || json.result == -2) {
                layer.msg("暂无数据...", { icon: 0 });
                if (params.view) {
                    document.getElementById(params.view).innerHTML = "";
                }
                if (params.element) {
                    document.getElementById(params.element).style.display = "none";
                }
            }
            else if (json.code < 0 || json.result < 0) {
                layer.msg(msg, { icon: 2 }, function () {
                    if (params.refresh) {
                        window.location.reload();
                    }
                    if (params.err_jumpurl) {//是否跳转链接                        
                        setTimeout(function () { location.href = params.err_jumpurl; }, 2000)
                    }
                });
            }
            if (params.tpl && (json.code > 0 || json.result > 0)) {
                if (params.opendiv && totalRows > 1000) {
                    //不在渲染模板
                }
                else {
                    var rows = eval(params.rows);
                    if (params.isparse)
                        rows = JSON.parse(rows);
                    layui.use('laytpl', function () {
                        var laytpl = layui.laytpl;
                        var Tpl = document.getElementById(params.tpl).innerHTML;
                        var View = document.getElementById(params.view);
                        laytpl(Tpl).render(rows, function (html) {
                            if (params.clear) {
                                View.innerHTML = html;
                            } else if (params.tplafter) {
                                View.innerHTML = html + View.innerHTML;
                            } else {
                                View.innerHTML += html;
                            }
                        })
                    })
                    //pageFlag = params.page;
                    if (params.page && json.code > 0 && pageFlag) {
                        SetPage(params, json);
                    }
                }
            }

            if (params.istree) {
                //makeTree(json.data.items,json.data.departs_checked, params.tree_params);
                makeTree_for_dtree(json.data.items, json.data.departs_checked, params.tree_params);
            }

            if (params.opendiv) {
                layer.closeAll();
                openDiv(params.div_title, params.div_elem, params.div_height, params.div_width);
            }
            if (params.closediv) {
                setTimeout(function () { layer.closeAll() }, 2000);
            }
            if (params.storage_clear) {
                localStorage.clear();
                sessionStorage.clear();
            }
            //是否将结果返回以作他用，如保留到浏览器缓存
            if (params.save && params.local_name != "" && (json.code > 0 || json.result > 0)) {
                if (params.storagerefresh) {
                    if (json.data)
                        sessionStorage.setItem(params.local_name, JSON.stringify(json.data));//这里本来用的sessionStorage,因为sessionStorage在页面关闭后回自动清除，为了方便改为localStorage//根据项目需要修改，本项目需要改为sessionStorage                    
                    else if (json.RetValue)
                        sessionStorage.setItem(params.local_name, JSON.stringify(json.RetValue));
                }
                else if (!sessionStorage.getItem(params.local_name)) {
                    if (json.data)
                        sessionStorage.setItem(params.local_name, JSON.stringify(json.data));
                    else if (json.RetValue)
                        sessionStorage.setItem(params.local_name, JSON.stringify(json.RetValue));
                }
            }
            if (params.formRender) {
                layui.use('form', function () {
                    var form = layui.form;
                    setTimeout(function () {
                        form.render('checkbox');
                        form.render('select');
                        form.render('radio');
                    }, 200);
                });
            }

        },
        error: function () {
            layer.closeAll('loading');
            layer.alert("Oops...something must go wrong", { icon: 5 });
        }
    })
    return ret;
}

//采用es6中的promise封装ajax，实现异步串行操作（不支持ie）
function ajax(method, url, data) {
    var request = new XMLHttpRequest();
    return new Promise(function (resolve, reject) {
        request.onreadystatechange = function () {
            if (request.readyState === 4) {
                if (request.status === 200) {
                    resolve(request.responseText);
                } else {
                    reject(request.status);
                }
            }
        };
        request.open(method, url);
        request.send(data);
    });
}

//删除或修改
function UpdateItem(url, data, msg) {
    layer.confirm(msg, {
        btn: ['确定', '取消']
    }, function () {
        var params = {
            'url': url,
            'type': 'post',
            'data': data,
            'controller': true,
            'showMsg': true,
            'refresh': true
        };
        sendAjax(params);
        //loadPage();
    }, function () {
        layer.closeAll();
    })
}

//弹出层-初级封装
function openDiv(title, elem, width, height, istpl=false) {
    var area = ['800px', '500px'];
    if (width && height) {
        area = [width, height];
    }
    var content = $('#' + elem + '');
    if (istpl)
        content = $('#' + elem + '').html();
    layer.open({
        type: 1,
        shade: [0.7, '#393D49'],
        title: title, //不显示标题
        area: area, //宽高
        anim: 2,
        shadeClose: true, //开启遮罩关闭
        content: content, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        cancel: function (index) {
            $('#' + elem + '').hide();
        }
    });
}

//弹出层-iframe
function openIframe(title, url, width, height) {
    var area = ['893px', '600px'];
    if (width && height) {
        area = [width, height];
    }
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: false,
        maxmin: true, //开启最大化最小化按钮
        area: area,
        content: url
    });
}

//渲染table
function getTable(params) {
    if (!params.height)
        params.height = 860;
    layui.use('table', function () {
        var table = layui.table;
        //第一个实例
        table.render({
            elem: params.elem
            , height: params.height
            , url: params.url //数据接口          
            , page: params.page //开启分页
            , headers: params.headers
            , limit: 10
            //, skin: 'row' //行边框风格
            , size: params.size
            , where: params.where
            , parseData: function (res) { //res 即为原始返回的数据
                if (res.code == 1) {
                    if (params.save && params.local_name) {
                        if (params.local)
                            localStorage.setItem(params.local_name, JSON.stringify(res.data));
                        else
                            sessionStorage.setItem(params.local_name, JSON.stringify(res.data));
                    }
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.message, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.items, //解析数据列表                            
                    }
                }
                else if (res.code == 0) {
                    layer.msg("" + "" + res.message + "", { icon: 0 });
                    return;
                }

            }
            , request: {
                pageName: 'pageindex' //页码的参数名称，默认：page
                , limitName: 'pagesize' //每页数据量的参数名，默认：limit
            }
            , response: {
                statusCode: 1 //规定成功的状态码，默认：0 
            }
            , cols: [params.cols]
            , done: function (res, curr, count) {
                //if (count == 0) {
                //    layer.msg("暂无数据...", { icon: 0 });
                //}
                for (var i = 0; i < count; i++) {
                    chargeTpl(params.tpl, params.view, i + 1, false);
                }
                //layer.msg(curr);

            }
        });
    });
}

//上传图片
function uploadFile(elem, url, name, isMultiple) {
    if (isMultiple == 0)
        isMultiple = true;
    else
        isMultiple = false;//默认关闭多文件上传
    if (!name)
        name = "files[]";
    layui.use('upload', function () {
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#' + elem + '' //绑定元素
            , url: url //上传接口
            , multiple: isMultiple
            , accept: 'file'
            , exts: 'pdf|doc|docx|xls|xlsx'
            , size: 1024 * 100 //最大文件大小为100M
            , before: function (obj) {

                layer.load();
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    var file_name = $('#doc_name').val();
                    if (!file_name)
                        $('#doc_name').val(file.name);
                    if (file.name.indexOf(".doc") > 0 || file.name.indexOf(".docx") > 0) {
                        layer.msg("word文件上传后，后台需要转换时间，转换过程可能出现问题，如出现转换失败等提示，请自行将word文件转换成pdf后在进行上传", { icon: 0, time: 5000 });
                    }
                });
            }
            , done: function (res) {
                layer.closeAll("loading");
                //上传完毕回调
                if (res.code == 1) {
                    layer.msg("上传成功", { icon: 1 });
                    var items = res.data.items;
                    for (var i = 0; i < res.data.total; i++) {
                        //var dom = '<input type="hidden" name="' + name + '" value="' + base_url + paths[i] + '"/>';
                        var dom = '<input type="hidden" name="' + name + '" value="' + items[i].id + '" id="hid_' + items[i].id + '" />';
                        $('#files_submit').append(dom);
                        if (isMultiple)
                            $('#demo2').append('<a id="resource_' + items[i].id + '" onclick=del_file("' + items[i].id + '") href="javascript:;" title="点击删除"><blockquote class="layui-elem-quote layui-quote-nm slickButton">' + items[i].file_name + '</blockquote></a>');
                        else
                            $('#demo2').html('<a id="resource_' + items[i].id + '" onclick=del_file("' + items[i].id + '") href="javascript:;" title="点击删除"><blockquote class="layui-elem-quote layui-quote-nm slickButton">' + items[i].file_name + '</blockquote></a>');
                    }
                }
                else if (res.code == 2) {
                    layer.confirm("存在重名文件，是否覆盖(选择'覆盖'则覆盖原文件，选择'并存'则重名文件会自动加以时间戳后缀'如A_10400051482.pdf')", { btn: ["覆盖", "并存"] },
                        function () {
                            uploadInst.config.url += "?iscover=1";
                            uploadInst.upload();
                        }, function () {
                            uploadInst.config.url += "?iscover=2";
                            uploadInst.upload();
                        }
                    )
                }
                else {
                    layer.msg(res.message, { icon: 2 });
                }
            }
            , error: function () {
                //请求异常回调
                layer.msg("网络异常", { icon: 2 });
                layer.closeAll();
            }
        });
    });
}


//地区选择
function initCityPicker(elem, init) {
    var currentPicker;
    layui.use(['jquery', 'table'], function () {
        var $ = layui.$
            , table = layui.table
            , form = layui.form
            , cityPicker = layui.citypicker;

        currentPicker = new cityPicker("#" + elem + "", {
            provincename: "provinceId",
            cityname: "cityId",
            districtname: "districtId",
            level: 'cityId',// 级别
        });
        if (init) {
            currentPicker.setValue(init);
        }
    });
    return currentPicker;
}

//格式化时间
function timeFormatter(value, formmat) {
    var da = new Date(parseInt(value.replace("/Date(", "").replace(")/", "").split("+")[0]));
    if (formmat == 1)
        return da.getFullYear() + "-" + ((da.getMonth() + 1) < 10 ? "0" + (da.getMonth() + 1) : (da.getMonth() + 1)) + "-" + (da.getDate() < 10 ? "0" + da.getDate() : da.getDate()) + " " + (da.getHours() < 10 ? "0" + da.getHours() : da.getHours()) + ":" + (da.getMinutes() < 10 ? "0" + da.getMinutes() : da.getMinutes()) + ":" + (da.getSeconds() < 10 ? "0" + da.getSeconds() : da.getSeconds());
    else
        return da.getFullYear() + "-" + ((da.getMonth() + 1) < 10 ? "0" + (da.getMonth() + 1) : (da.getMonth() + 1)) + "-" + (da.getDate() < 10 ? "0" + da.getDate() : da.getDate());
}

//设定分页
function SetPage(params, json) {
    pageFlag = false;
    layui.use('laypage', function () {
        var laypage = layui.laypage;
        laypage.render({
            elem: 'page',
            count: json.data.total,
            limit: params.data.pageSize,
            limits: pageLimits,
            layout: ['count', 'prev', 'page', 'next', 'skip', 'limit'],
            jump: function (obj, first) {
                if (!first) {
                    params.clear = true;
                    params.data.pageIndex = obj.curr;
                    params.data.pageSize = obj.limit;
                    sendAjax(params);
                }
            }
        })
    })
}

//获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//取cookie
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    }
    else {
        return null;
    }
}

//删cookie
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) {
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }
}

//弹出层-图片
function layerImg(src, title, area) {
    layer.open({
        type: 1,
        title: title,
        closeBtn: 1,
        area: area,
        offset: 'auto',
        skin: 'layui-layer-nobg', //没有背景色
        shadeClose: true,
        content: "<div style='text-align:center'><img src='" + src + "' id='bank_a'></div>"
    });
}

//扩展数组属性-包含
Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
//扩展数组属性-删除
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
//数组排重 es6
function unique1(arr) {
    var hash = [];
    for (var i = 0; i < arr.length; i++) {
        if (hash.indexOf(arr[i]) == -1) {
            hash.push(arr[i]);
        }
    }
    return hash;
}

function setLocalStorage(key, value) {
    var curtime = new Date().getTime(); // 获取当前时间 ，转换成JSON字符串序列 
    var valueDate = JSON.stringify({
        val: value,
        timer: curtime
    });
    try {
        localStorage.setItem(key, valueDate);
    } catch (e) {
        /*if(e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
            console.log("Error: 本地存储超过限制");
            localStorage.clear();
        } else {
            console.log("Error: 保存到本地存储失败");
        }*/
        // 兼容性写法
        if (isQuotaExceeded(e)) {
            console.log("Error: 本地存储超过限制");
            localStorage.clear();
        } else {
            console.log("Error: 保存到本地存储失败");
        }
    }
}

function isQuotaExceeded(e) {
    var quotaExceeded = false;
    if (e) {
        if (e.code) {
            switch (e.code) {
                case 22:
                    quotaExceeded = true;
                    break;
                case 1014: // Firefox 
                    if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
                        quotaExceeded = true;
                    }
                    break;
            }
        } else if (e.number === -2147024882) { // IE8 
            quotaExceeded = true;
        }
    }
    return quotaExceeded;
}

function getLocalStorage(key) {
    var exp = 60 * 60 * 24; // 一天的秒数
    if (localStorage.getItem(key)) {
        var vals = localStorage.getItem(key); // 获取本地存储的值 
        var dataObj = JSON.parse(vals); // 将字符串转换成JSON对象
        // 如果(当前时间 - 存储的元素在创建时候设置的时间) > 过期时间 
        var isTimed = (new Date().getTime() - dataObj.timer) > exp;
        if (isTimed) {
            console.log("存储已过期");
            localStorage.removeItem(key);
            return null;
        } else {
            var newValue = dataObj.val;
        }
        return newValue;
    } else {
        return null;
    }
}